const getNowTime = () => {
  let time = new Date();
  let year = time.getFullYear();
  let mon = time.getMonth() + 1;
  let day = time.getDate();
  let hour = time.getHours();
  let min = time.getMinutes();
  let sec = time.getSeconds();

  // 判断时间是否大于等于10，不大于10就在前面添加0
  const setZero = (t) => {
    return t >= 10 ? t : "0" + t;
  };

  return `${year}-${setZero(mon)}-${setZero(day)} ${setZero(hour)}:${setZero(
    min
  )}:${setZero(sec)}`;
};

// 提取id
let keyword = document.getElementById("keyword");
let pop = document.getElementById("pop");
let popTitle = document.getElementById("popTitle");
let title = document.getElementById("title");
let content = document.getElementById("content");
let lists = document.getElementById("lists");
let isFormEdit = false;
let listIdx;
// 搜索功能
const search = () => {
  let keywordVal = keyword.value.toLowerCase();

  let items = lists.querySelectorAll(".list");
  items.forEach((item) => {
    let t = item.querySelector(".list-title").innerText.toLowerCase();
    item.style.display = t.includes(keywordVal) ? "block" : "none";
  });
};

// 点击添加事件

const changePop = (t = '添加', list = null, isEdit = false) => {

  pop.style.visibility = "visible";
  pop.style.opacity = 1;
  // 设置标题
  popTitle.innerText = t;
  isFormEdit = isEdit;
  if (isEdit) {
    // 给列表生成唯一标识
    listIdx = list.idx;
    // 数据赋值
    title.value = list.title;
    content.value = list.content;
  } else {
    // 没有编辑 清空数据
    title.value = "";
    content.value = "";
  }
};

// 取消功能
const cancel = () => {
  pop.style.visibility = "hidden";
  pop.style.opacity = 0;
};

// 删除功能
const del = (i) => {
  lists.removeChild(lists.querySelector(`#lists${i}`));
};

// 确认表单元素
const save = () => {
  // 必须添加标题
  if (title.value) {
    if (isFormEdit) {
      let list = document.getElementById(`lists${listIdx}`);
      // 更新标题和描述
      list.querySelector(".list-title").innerText = title.value;
      list.querySelector(".list-content").innerText = content.value;
    } else {
      let listLength = lists.querySelectorAll(".list").length;
      let listForm = JSON.stringify({
        idx: listLength,
        title: title.value,
        content: content.value,
      });
      // 添加一个子列表
      lists.innerHTML += `<li class="list" id="lists${listLength}" class="mg_top20 mg_left20">
				<div class="flex justify-between ">
					<div class="list-title mg_top20 mg_left20" >${title.value}</div>
					<button onclick='changePop("编辑", ${listForm}, true)' class="color_blue button02 mg_top20 ">编辑</button>
				</div>
				<div class="list-content mg_top20 mg_left20">${content.value}</div>
				<div class="flex justify-between">
					<div class="list-time mg_top20 mg_left20">${getNowTime()}</div>
					<button onclick="del(${listLength})" class="color_zs button02 mg_top20 ">删除</button>
				</div>
			</li>`;
    }
    // 取消弹框
    cancel();
  } else alert("请添加标题！");
};